package com.adopapa.nezhacloud.register.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.adopapa.nezhacloud.common.DataType;
import com.adopapa.nezhacloud.common.RestResponse;
import com.adopapa.nezhacloud.common.Tools;
import com.adopapa.nezhacloud.ddd.conf.AppConstants;
import com.adopapa.nezhacloud.ddd.controller.BaseController;
import com.adopapa.nezhacloud.redis.RedisService;
import com.adopapa.nezhacloud.register.conf.RegisterConstants;
import com.adopapa.nezhacloud.register.domain.StudentInfo;
import com.adopapa.nezhacloud.register.service.DataSender;
import com.adopapa.nezhacloud.register.service.StudentInfoService;
import com.google.code.kaptcha.Producer;

@RestController
@RequestMapping("/register/studentinfo")
public class StudentInfoController extends BaseController {

	@Autowired
	private Producer captchaProducer;
	@Autowired
	private RedisService redisService;
	@Autowired
	private StudentInfoService studentInfoService;
	@Autowired
	private DataSender dataSender;

	@GetMapping(path = "/kaptcha.jpg", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse getKaptcha() {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			String capText = captchaProducer.createText();
			logger.info(capText);

			RedisTemplate<String, Object> redisTemplate = //
					redisService.getRedisTemplate(RegisterConstants.REGISTER_REDIS_DBINDEX);
			redisTemplate.opsForValue().set(String.format("Kaptcha:%s", capText), capText, 300L, TimeUnit.SECONDS);

			BufferedImage bi = captchaProducer.createImage(capText);
			ImageIO.write(bi, "jpg", baos);

			String imageData = Base64.getEncoder().encodeToString(baos.toByteArray());
			imageData = DataType.IMAGE_JPG_BASE64.getValue().concat(imageData);

			baos.close();

			return RestResponse.ok(imageData);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			return RestResponse.error(e);
		}

	}

	@GetMapping(path = "/studentinfos/{pageNo}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse getStudentInfoPage(@RequestHeader String authorization, //
			@PathVariable Integer pageNo, //
			@RequestParam(required = false) String name, //
			@RequestParam(required = false) String cellphone, //
			@RequestParam(required = false) String career, //
			@RequestParam(required = false) String province, //
			@RequestParam(required = false) String city, //
			@RequestParam(required = false) String town, //
			@RequestParam(required = false) String createTime, //
			@RequestParam(required = false) String createTime2, //
			@RequestParam(required = false) Integer pageSize) {

		StudentInfo studentInfo = new StudentInfo();

		studentInfo.setName(name);
		studentInfo.setCellphone(cellphone);
		studentInfo.setCareer(career);
		studentInfo.setProvince(province);
		studentInfo.setCity(city);
		studentInfo.setTown(town);

		Instant createTimeInstant = Tools.fromTimeStr(createTime);
		studentInfo.setCreateTime(createTimeInstant);
		Instant createTime2Instant = Tools.fromTimeStr(createTime2);
		studentInfo.setCreateTime2(createTime2Instant);

		pageSize = Tools.empty(pageSize) ? AppConstants.DEFAULT_PAGE_SIZE : pageSize;

		Page<StudentInfo> page = studentInfoService.getStudentInfoPage(pageNo, pageSize, studentInfo);

		return RestResponse.ok(page);
	}

	@GetMapping(path = "/studentinfo/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse getHappyDemo(@RequestHeader String authorization, //
			@PathVariable String id) {
		StudentInfo studentInfo = studentInfoService.getStudentInfoById(id);
		return RestResponse.ok(studentInfo);
	}

//	@CrossOrigin
	@PostMapping(path = "/studentinfos", produces = MediaType.APPLICATION_JSON_VALUE, //
			consumes = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse saveStudentInfo(@RequestHeader String authorization, //
			@RequestBody Map<String, Object> params) {

		String id = getMapValue(params, "id", String.class);

		String name = getMapValue(params, "name", String.class);
		String cellphone = getMapValue(params, "cellphone", String.class);
		String career = getMapValue(params, "career", String.class);
		String province = getMapValue(params, "province", String.class);
		String city = getMapValue(params, "city", String.class);
		String town = getMapValue(params, "town", String.class);
		String doulin = getMapValue(params, "doulin", String.class);
		String fanstr = getMapValue(params, "fans", String.class);

		Long fans = null;
		if (!Tools.empty(fanstr)) {
			fanstr = fanstr.trim();
			if (fanstr.endsWith("万")) {
				fanstr = fanstr.replace("万", "").trim();
				fans = Long.valueOf(fanstr) * 10000L;
			} else if (fanstr.endsWith("千")) {
				fanstr = fanstr.replace("千", "").trim();
				fans = Long.valueOf(fanstr) * 1000L;
			} else {
				try {
					fans = Long.valueOf(fanstr);
				} catch (Exception e) {
					logger.error(ExceptionUtils.getStackTrace(e));
				}
			}
		}

		if (Tools.empty(name)) {
			throw new RuntimeException("学员姓名不能为空");
		}
		if (Tools.empty(cellphone)) {
			throw new RuntimeException("手机号码不能为空");
		}
		if (Tools.empty(career)) {
			throw new RuntimeException("职业不能为空");
		}
		if (Tools.empty(province)) {
			throw new RuntimeException("所在省份不能为空");
		}
		if (Tools.empty(city)) {
			throw new RuntimeException("所在城市不能为空");
		}
		if (Tools.empty(town)) {
			throw new RuntimeException("所在区域不能为空");
		}
//		if (Tools.empty(doulin)) {
//			throw new RuntimeException("抖音号不能为空");
//		}
//		if (Tools.empty(fans)) {
//			throw new RuntimeException("粉丝数不能为空");
//		}

		RedisTemplate<String, Object> redisTemplate = //
				redisService.getRedisTemplate(RegisterConstants.REGISTER_REDIS_DBINDEX);

		String existed = (String) redisTemplate.opsForHash().get("student", cellphone);
		if (!Tools.empty(existed)) {
			if (!existed.equals(name)) {
				return RestResponse.other("手机号码已经注册");
			}
			return RestResponse.other("您已报名成功");
		}

//		StudentInfo existed = studentInfoService.getStudentInfoByCellphone(cellphone);
//		if (!Tools.empty(existed) ) {
//			if (!existed.getName().equals(name)) {
//				throw new RuntimeException("手机号码已经注册");
//			} 
//			return RestResponse.other("您已报名成功");
//		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("name", name);
		data.put("cellphone", cellphone);
		data.put("career", career);
		data.put("province", province);
		data.put("city", city);
		data.put("town", town);
		data.put("doulin", doulin);
		data.put("fans", fans);

		dataSender.send(data);

//
//		StudentInfo studentInfo = null;
//		if (Tools.empty(id)) {
//			studentInfo = new StudentInfo();
//			studentInfo.setCreateTime(Instant.now());
//		} else {
//			studentInfo = studentInfoService.getStudentInfoById(id);
//			if (Tools.empty(studentInfo)) {
//				throw new RuntimeException("指定id对应信息不存在");
//			}
//		}
//		studentInfo.setName(name);
//		studentInfo.setCellphone(cellphone);
//		studentInfo.setCareer(career);
//		studentInfo.setProvince(province);
//		studentInfo.setCity(city);
//		studentInfo.setTown(town);
//		studentInfo.setDoulin(doulin);
//		studentInfo.setFans(fans);
//		studentInfo.setUpdateTime(Instant.now());
//
//		studentInfoService.saveStudentInfo(studentInfo);

		return RestResponse.ok();

	}

	@DeleteMapping(path = "/studentinfo/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
	public RestResponse deleteStudentInfo(@RequestHeader String authorization, //
			@PathVariable String id) {
		try {
			studentInfoService.deleteStudentInfo(id);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
		}

		return RestResponse.ok();
	}

}
